import json
import os
import PIL
from PIL import Image

file_dir = r'H:\Deep_Learning\mmdetection2.0\mmdetection2.0\work_dirs\ciwa_seg\test\ng\ng/'
json_dir = r'H:\Deep_Learning\mmdetection2.0\mmdetection2.0\work_dirs\ciwa_seg\test\ng\ng/'
d = r'H:\Deep_Learning\mmdetection2.0\mmdetection2.0\work_dirs\ciwa_seg\test\ng\ng_det/'
datanames = os.listdir(file_dir)
# base_json = r'H:\磁瓦\101训练集\seg_coco\1/0_ng042710-1400-417-610-101.json'

# def create_json():
#     for dataname in datanames:
#         if os.path.splitext(dataname)[1] == '.jpg':
#             i = os.path.splitext(dataname)[0]
#         # 创建json
#             json = '{}.json'.format(str(i))
#             with open(json, 'w', encoding='utf-8') as f:
#                 # 写入内容
#                 f.write(dataname)
# create_json()

for dataname in datanames:
    if os.path.splitext(dataname)[1] == '.jpg':
        basename = os.path.splitext(dataname)[0]
        with Image.open(file_dir + dataname) as img:
            w, h = img.size
            # json_dict = {"version": "4.5.5", "flags": {}, "shapes": [], "imagePath": dataname,
            #              "imageData": "",   "imageHeight": h, "imageWidth": w}
            # os.makedirs(os.path.dirname(json_dir + basename + '.json'), exist_ok=True)
            # json_file = '{}.json'.format(str(basename))
            json_name = basename + '.json'
            with open(json_dir + json_name, 'r+', encoding='utf-8') as f:
                data = json.load(f)
                data["imageHeight"] = h
                data["imageWidth"] = w
                json_str = json.dumps(data)
                with open(d + json_name, 'w', encoding='utf-8') as j:
                    j.write(json_str)
                    j.close()
                f.close()


















            # data = json.load(open(base_json, 'r', encoding='utf-8'))
            # data['imagePath'] = dataname
            # data['imageHeight'] = h
            # data['imageWidth'] = w
            # data.write(basename + '.json')
